import React from 'react'
import {Tooltip, Upload} from 'antd';
import ImgCrop from 'antd-img-crop';
import {inject,observer} from "mobx-react";


@inject('management')
@observer
class Uploadpic extends React.Component{
    state = {
        fileList:[],
    }

    onChange= ({ fileList: newFileList }) =>{
        this.setState({
            fileList:newFileList
        },()=>{
            // 把图片数组存到mobx里
            this.props.management.upPic(newFileList)
        })

    }
    beforeUploadMains = () => { // 自定义上传事件
        return false; // 《《= 关键 阻止upload默认上传事件
    }
    onPreview = async file => {
        let src = file.url;
        if (!src) {
            src = await new Promise(resolve => {
                const reader = new FileReader();
                reader.readAsDataURL(file.originFileObj);
                reader.onload = () => resolve(reader.result);
            });
        }
        const image = new Image();
        image.src = src;
        const imgWindow = window.open(src);
        imgWindow.document.write(image.outerHTML);
    };
    render() {
        return (
            <ImgCrop rotate>
                <Tooltip placement="topLeft" title='请上传5张图片'>
                    <Upload
                        listType="picture-card"
                        fileList={this.state.fileList}
                        onChange={this.onChange}
                        onPreview={this.onPreview}
                        beforeUpload={this.beforeUploadMains}
                    >
                        {this.state.fileList.length < 5 && '+ 点击上传'}
                    </Upload>
                </Tooltip>
            </ImgCrop>
        )
    }
}


export default Uploadpic